#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     rest_flask
# @File:        keyword_matcher.py
# @Author:      Fan GuiChuan
# @Date:        2025/6/30 14:04
# @Version:     Python3.7
# @Description:
import ahocorasick


class KeywordMatcher:
    def __init__(self, keywords: list, keyword_ids):
        if keywords:
            self.keyword_ids = keyword_ids
            self.automation = ahocorasick.Automaton()

            for idx, keyword in enumerate(keywords):
                self.automation.add_word(keyword, (idx, keyword))

            self.automation.make_automaton()

    def match_all(self, data: str):
        result = []
        if self.automation:
            for end_pos, (idx, keyword) in self.automation.iter(data):
                from_ = end_pos - len(keyword) + 1
                result.append({
                    'feature_id': self.keyword_ids[idx]['label_id'],
                    'feature_name': self.keyword_ids[idx]['label_name'],
                    'level_id': self.keyword_ids[idx]['level_id'],
                    'level_code': self.keyword_ids[idx]['level_code'],
                    'rule_id': self.keyword_ids[idx]['rule_id'],
                    'template_id': self.keyword_ids[idx]['template_id'],
                    'from': from_,
                    'to': end_pos,
                    'match': keyword,  # 提取匹配文本
                    'identify_type_name': 'keyword',
                    'identify_type': 0
                })
        return result


if __name__ == '__main__':
    keyword_matcher = KeywordMatcher(['你好', '哈哈'])
    result = keyword_matcher.match_all('你好吗，哈哈哈哈哈')
    print(result)
